package com.windowes.weichang.service;

import com.windowes.weichang.common.ServerResponse;
import com.windowes.weichang.dao.DemandMapper;
import com.windowes.weichang.model.BDShop;
import com.windowes.weichang.pojo.Demand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/***
 *
 * @author: yangqing
 * @email: qing.yang@bangdao-tech.com
 * @createTime: 2018/6/24 下午7:13
 * @description: 案例
 *
 **/
@Service
public class CaseService {


    @Autowired
    AMapService aMapService;
    @Autowired
    DemandMapper demandMapper;


    /**
     * @param region 市、区
     * @return
     */
    public ServerResponse list(String region) {
        ServerResponse<List<BDShop>> geosearch = aMapService.geosearch(region, "");
        if (!geosearch.isSuccess()) {
            return ServerResponse.createByErrorMessage("未查询到数据!");
        }

        List<BDShop> bdShops = geosearch.getData();
        List<Integer> shopIds = bdShops.stream().map(BDShop::getShopId).collect(Collectors.toList());
        List<Demand> demands = demandMapper.selectByShopIds(shopIds);
        if (demands != null && !demands.isEmpty()) {
            if (demands.size() > 10) {
                //随机取
                int[] randomIds = randomCommon(0, demands.size(), 10);
                List<Demand> demandList = new ArrayList<>();
                for (int idx = 0; idx < randomIds.length; idx++) {
                    demandList.add(demands.get(randomIds[idx]));
                }
                return ServerResponse.createBySuccess("获取成功!", demandList);
            }
            return ServerResponse.createBySuccess("获取成功!", demands);
        }
        return ServerResponse.createByErrorMessage("未查询到数据!");
    }


    /**
     * 随机指定范围内N个不重复的数
     *
     * @param min 指定范围最小值
     * @param max 指定范围最大值
     * @param n   随机数个数
     */
    public static int[] randomCommon(int min, int max, int n) {
        if (n > (max - min + 1) || max < min) {
            return null;
        }
        int[] result = new int[n];
        int count = 0;
        while (count < n) {
            int num = (int) (Math.random() * (max - min)) + min;
            boolean flag = true;
            for (int j = 0; j < n; j++) {
                if (num == result[j]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                result[count] = num;
                count++;
            }
        }
        return result;
    }


}
